from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import celery_send_sms_code
from utils.captcha.captcha import captcha

class ImageCodeView(View):
    def get(self, request, uuid):
        # 步骤
        # 1 获取uuid
        print(uuid)
        # 2 生成图片验证码 和二进制图片数据
        text, image = captcha.generate_captcha()
        print(text)
        # 3 redis保存验证码 用uuid为key 有效期
        redis_cli = get_redis_connection("code")
        # uuid为key  120s是过期时间
        redis_cli.setex(uuid, 120, text)
        # 4 返回二进制图片数据
        return HttpResponse(image, content_type='image/jpeg')



class SmsCodeView(View):
    def get(self, request, mobile):
        # 获取参数
        image_code = request.GET.get("image_code")
        uuid = request.GET.get("image_code_id")

        print('11111111111',image_code)
        print('22222222',uuid)
        # 判断参数是否完整
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': "参数不全"})
        # 连接redis 根据uuid取验证码
        redis_cli = get_redis_connection("code")
        redis_image_code = redis_cli.get(uuid)
        # 删除验证码
        try:
            redis_cli.delete()
        except Exception as e:
            print("删除图片验证码")
        # 如果没有验证码 验证码过期
        if redis_image_code is None:
            return JsonResponse({'code': 400, 'errmsg': "图片验证码过期"})

        from random import randint
        # 生成随机短信验证码
        sms_code = "%06d" % randint(0, 999999)
        print(sms_code)

        # 防止短信验证码频繁发送
        send_flag = redis_cli.get("send_flag_%s" % mobile)
        # print("--------",send_flag)
        # 如果有send_flag 说明之前发送过了
        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': "发送短信过于频繁"})

        # redis管道
        p1 = redis_cli.pipeline()
        # 保存 短信验证码到redis
        p1.setex("sms_%s" % mobile, 300, sms_code)
        p1.setex("send_flag_%s" % mobile,60,1)
        # 执行请求
        p1.execute()
        # 把号码传入 发送短信里
        # SmsUtil().send_message(mobile, (sms_code, 5))
        celery_send_sms_code.delay(mobile, sms_code)
        return JsonResponse({'code': 0, 'errmsg': "ok"})